package com.vue.admin.service.common.jwt;

import com.vue.admin.service.common.exception.ResponseEntity;
import com.vue.admin.service.common.util.JsonUtils;
import org.apache.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: vue-admin-service
 * @description: JWT filter
 * @author: zhangyangyang
 * @create: 2020-04-03 13:42
 **/
public class JwtFilter extends AuthenticatingFilter {

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        // 获取请求token
        String token = this.getRequestToken((HttpServletRequest)request);
        if(token == null || token.equals("")) {
            return null;
        }
        return new JwtToken(token);
    }

    /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest) {
        // 从header中获取token
        String token = httpRequest.getHeader("token");
        // 如果header中不存在token，则从参数中获取token
        if(token == null || token.equals("")) {
            token = httpRequest.getParameter("token");
        }
        return token;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return false;
    }

    /**
     * 检查token
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        // 获取请求token，如果token不存在，直接返回401
        String token = this.getRequestToken((HttpServletRequest)request);
        if(token == null || token.equals("")) {
            HttpServletResponse httpResponse = (HttpServletResponse)response;
            ResponseEntity r = ResponseEntity.error(HttpStatus.SC_UNAUTHORIZED, "SERVER_EXCEPTION_INVALID_TOKEN");
            String json = JsonUtils.beanToJson(r);
            httpResponse.getWriter().print(json);
            return false;
        }
        return this.executeLogin(request, response);
    }

    /**
     * 登录失败
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
                                     ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse)response;
        httpResponse.setContentType("application/json;charset=utf-8");
        try {
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            ResponseEntity r = ResponseEntity.error(HttpStatus.SC_UNAUTHORIZED, throwable.getMessage());
            String json = JsonUtils.beanToJson(r);
            httpResponse.getWriter().print(json);
        } catch(Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }
}
